<?php
	include_once '../models/Model.php';
	
	//generate timestamp between 2 given date
	function dates_range($date1, $date2) 
	{ 
	   if ($date1<=$date2) 
	   { 
	       $date1=strtotime($date1); 
	       $date2=strtotime($date2);
	       $dates_range[]=$date1;  
	       while ($date1!=$date2) 
	       { 
	           $date1=mktime(0, 0, 0, date("m", $date1), date("d", $date1)+1, date("Y", $date1)); 
	           $dates_range[]=$date1; 
	       } 
	   } 
	   return $dates_range; 
	} 
	
	//init all time in date,flag=0
	function init_time_array($date)
	{
		foreach(range(0,23) as $hour)
		{
			$time[]=array('time'=>date('Y-m-d H:i:s',mktime($hour,0,0,date("m",$date),date("d",$date), date("Y",$date))),"flag"=>0);
			$time[]=array('time'=>date('Y-m-d H:i:s',mktime($hour,30,0,date("m",$date),date("d",$date), date("Y"),$date)),"flag"=>0);
		}	
		return $time;	
	}
	
	$model=new Model();
	//get room name
	$name=substr($_POST['name'],-1);
	//get room id
	$room=$model->searchRoomByName($name);
	$roomId=$room->getRoomId();
	
	//get order start time & end time ,generate date range between them
	
	$orderStartTime=date('Y-m-d',strtotime($_POST['orderStartTime']));
	$orderEndTime=date('Y-m-d',strtotime($_POST['orderEndTime']));
	
	// check whether input time is valid or not
	
	$now=mktime(0,0,0,date('m'),date('d'),date('Y'));
	$startTime=strtotime($orderStartTime);
	$endTime=strtotime($orderEndTime);
	
	if( $startTime>$endTime || $startTime<$now || $endTime<$now)
	{
		echo "<script type='text/javascript'>\n";
		echo "alert('Invalid input time');\n";
		echo "window.location='../view/user/book_room.php'";
		echo "</script>";	
	}
	
	if($_POST['orderStartTime']&&$_POST['orderEndTime']&&$orderStartTime<=$orderEndTime)
	{		
		$date_range=dates_range($orderStartTime,$orderEndTime);
		
		//generate bookable time for each date
		
		foreach($date_range as $date)
		{	
	
			$date=date('Y-m-d',$date);
		
			$order=$model->searchAvailable($date,$roomId);
			//var_dump($order);die;
			
			//get all bookable hour,init flag=0
			$time=init_time_array(strtotime($date));
			// get all booked time 
			if($order!=null)
			{
			foreach($order as $item)
				if($item->getOrderStatus()==1)
					$orderedTime[]=array('startTime'=>$item->getOrderStartTime(),'endTime'=>$item->getOrderEndTime());
			//var_dump($orderedTime);die;
					//set flag=1 if room is booked at this time
			if($orderedTime!=null)			
				foreach($time as $key=>$element)
					foreach($orderedTime as $item)
						if($element['time']>=$item['startTime']&&$element['time']<=$item['endTime'])
						{
						//echo $element['time'];
							$element['flag']=1;
							$time[$key]=$element;
						}		
			}
			$outputTime[]=$time;	
		}			
	}
	else
		$outputTime='none';
	include_once '../view/user/view_book_room.php';
?>	
	
	